// pages/service_choice.js
var app = getApp();
var reqHelp = require('../../utils/reqHelp.js');
import Toast from '@vant/weapp/toast/toast';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        cardIccid:'',//卡号
        mealList:[],
        dtMealTime:[],
        dtMealUsage:[],
        mealTime:'',
        mealshow:false,// 是否显示弹窗框
        specialMealshow:false,//
        payShow:false,// 显示支付弹窗
        showAlert:false,//是否显示提示弹框
        mealId:0,
        mealPrice:'',
        mealName:'',
        userId: '',
        uAvatar: '',
        userOpenId: '',
        cardId: '',
        warningMessage:'',
        group:'',
        platId:'',
        restMoney:0,
        checkRules:true,
        notRecomMeal:{},
        recommenedMeal:{},
        parMeal:{}
    },
    onClose(){
        this.setData({ mealshow: false,specialMealshow:false });
    },
    onCheckRules(){
      const that =this;
      this.setData({
        checkRules: !that.data.checkRules
      })
   
    },
    selectMeal(e){
        console.log(e)
        const mealId = e.currentTarget.dataset.item.pro_id
        const name = e.currentTarget.dataset.item.pro_name
        const mealMarketPrice = e.currentTarget.dataset.item.pro_marketprice
        const platId = e.currentTarget.dataset.item.platId
        const pairId = e.currentTarget.dataset.item.pro_pair
        const groupID = e.currentTarget.dataset.pitem.platGroup
        const group = groupID ==1?'usage':'time'
        this.setData({
           mealId:mealId,
           mealName:name,
           mealPrice: mealMarketPrice,
           group:group,
           platId:platId
        })
        console.log(pairId)
      if(pairId == 0){
        this.getMealDetail(mealId)
      }else{
        this.getMealDetailSpecial(pairId)
      }
    },
    getMealDetailSpecial(pairId){
      var that = this;
      reqHelp.requestByJson(app.globalData.apiUrlNew+'Mini/BalUpdated.ashx?action=mealPair', {
        pairId: pairId,
        cardId: that.data.cardId,
      }).then(function (res) {
       console.log(res)
       if (res.getNum == 0) {
        const pair_memo = JSON.parse(res.objPair.pair_memo)
        console.log(pair_memo)
        res.objPair.pair_memo = pair_memo
        that.setData({
          specialMealshow: true,
          parMeal: res.objPair,
          recommenedMeal: that.getRecommenedMeal(res.dtMealPair,true),
          notRecomMeal: that.getRecommenedMeal(res.dtMealPair,false)
        })
       }
     });
    },
    getRecommenedMeal(dtMealPair,bol){
      let arr1= dtMealPair[0]
      let arr2= dtMealPair[1]
      let recod
      if(bol){
        //如果bol为true的话，返回推荐客户购买的套餐
        recod = arr1.pro_marketprice>arr2.pro_marketprice?arr1:arr2
      }else{
        recod = arr1.pro_marketprice>arr2.pro_marketprice?arr2:arr1
      }
      return recod
    },
    getMealDetail(mealId){
      var that = this;
       reqHelp.requestByJson(app.globalData.apiUrlNew+'Mini/BalUpdated.ashx?action=mealCheck', {
         cardId: that.data.cardId,
         userId: that.data.userId,
         mealId: mealId
       }).then(function (res) {
        console.log(res)
        if (res.getNum == 0) {
         that.setData({ mealshow: true });
          that.setData({
            mealTime: '到期日: ' + res.dateEnd,
            objActivity:res.objActivity,
            objVoucher:res.objVoucher,
            // lastPay: res.mealMarketPrice - that.data.restMoney - res.objVoucher.vouMoneyPrice - res.objActivity.actMarketPrice
          });
        }else if(res.getNum ==10){
          that.setData({
            warningMessage:res.getMsg,
            showAlert:true,
          })  
        } else {
          that.setData({
            mealName: res.getMsg,
          });
        }
      });
    },
    getNewMeal(cardId,userId){
      const that = this
      wx.request({
        url: 'https://h501.zhusiot.com/Mini/BalUpdated.ashx?action=mealInit',//app.globalData.apiUrlNew + 
        data: {
          cardId:cardId,
          userId:userId
        },
        dataType: 'json',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(resroom) {
          const result = resroom.data;
          console.log(resroom)
          if (result.getNum == 0) {
            var arrPlat = [],
            arrMeal = [],
            arrPlatList = [];
            arrPlat = result.dtPlat;
            arrMeal = result.dtMeal;
            arrMeal.map(item=>{
              if(item.pro_exContent){
                item.pro_exContent =JSON.parse(item.pro_exContent)
              }
            })
            arrPlat.map(item => {
               item.platMeal = that.strToArray1(arrMeal, item.platId); 
               arrPlatList.push(item);
            })
            that.setData({
               dtMealTime: arrPlatList,
              // dtMealUsage:that.strToArray(result.dtMeal,1),
              objCard: result.objCard,
              restMoney:result.objCard.bank_rest
            });
          } else if (result.getNum == 5) {
            // wx.redirectTo({
            //   url: 'regMealSure?cardId=' + cardId,
            // })
          } else {
              console.log(cardId)
            //  wx.redirectTo({
            //     url: '../index/index?cardId=' + cardId,
            //   })
            // that.setData({
            //   cardIccid: result.getMsg,
            //   btnPayDisable: true
            // });
          }
        }
      })
    },

    strToArray(arr,platGroup){
     let newArr=[]  
     let platID 
     if(arr.length>0){
        arr.map(item=>{
            if(item.platGroup == platGroup){
                platID = item.platId
                if(item.mealList.length>0){
                    newArr = JSON.parse(item.mealList)
                }
            }
        }) 
        if(newArr.length>0){
            newArr.map(item=>{
                item.platId = platID
            })
        }
     }
     console.log(newArr)
    return newArr
    },
    payPairMeal(e){
      const id = e.currentTarget.dataset.meal
      console.log(id)
      this.setData({
        mealId:id 
      })
      this.onPay()
    },
    // 点击 立即付款按钮
    onPay(){
        const that = this;
        if(!this.data.checkRules){
          Toast('请同意套餐协议')
          return 
        }
        wx.request({
            url: app.globalData.apiUrlNew + 'Mini/BalUpdated.ashx?action=mealPay',
            data: {
              userId: that.data.userId,
              mealId: that.data.mealId,
              cardId: that.data.cardId,
              userOpenId: that.data.userOpenId,
              platId:that.data.platId
            },
            dataType: 'json',
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(resp) {
              console.log(resp)
              var respd = resp.data;
              if (respd.getNum == 5) {
                const {
                  timeStamp,
                  nonceStr,
                  mnpPackage,
                  paySign
                } = respd;
                wx.requestPayment({
                  nonceStr: nonceStr,
                  package: mnpPackage,
                  signType: "RSA",
                  paySign: paySign,
                  timeStamp: timeStamp,
                  success: function (resPay) {
                   // 支付成功
                   wx.redirectTo({
                      url: '../../pages/handle_result/handle_result?resultId=1',
                    })
                  },
                  fail: function (resPay) {
                    if (resPay.errMsg == "requestPayment:fail cancel") {
                        // 支付取消
                        that.setData({
                            showAlert:true,
                            warningMessage:'支付失败，你的交易取消',
                            mealshow:false,
                            specialMealshow:false
                        })
                    } else {
                        // 支付失败
                    wx.redirectTo({
                        url: '../../pages/handle_result/handle_result?resultId=2',
                      })
                    }
                  },
                  complete: function (res) {}
                })
              } else if (respd.getNum == 0) {
                  //预充值已生效
                  Toast({
                    type: 'success',
                    message: '预充值已生效',
                    onClose: () => {
                        wx.redirectTo({
                            url: '../index/index?card=' + that.data.cardId,
                          })
                    },
                  });
              } else {
                console.log(respd)
                that.setData({
                    showAlert:true,
                    warningMessage:respd.getMsg,
                    mealshow:false,
                    specialMealshow:false
                })
              }
            },
            fail(resfail) {
                console.log.log(resfail)
                that.setData({
                    showAlert:true,
                    warningMessage:resfail.data.getMsg,
                    mealshow:false,
                    specialMealshow:false
                })
            }
        })
    },
    /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.selectComponent("#loading").show()
    const that = this;
    const cardId = options.cardId; //'22807';//
    //const cardId = '22807'
    app.getLogUser(function (uInfo) {
      const {userId,userOpenId} = uInfo;
      that.setData({
        userId: userId,
        userOpenId:userOpenId,
        cardId: cardId
      })
      that.getNewMeal(cardId,userId)
      that.selectComponent("#loading").hide()
    });
  },
  strToArray1(arrMeal, platId) {
    let newArr = [];
    // dic_name AS platName,dic_power AS platId,dic_group AS platGroup,NULL AS platMeal
    if (arrMeal.length > 0) {
      arrMeal.map(item => {
        if (item.platId == platId) {
          // item.pro_exContent=JSON.parse(item.pro_exContent);
            newArr.push(item); 
        }
      })
    }
    return newArr
  },
})